import 'package:flutter/material.dart';
import 'package:google_fonts/google_fonts.dart';
import 'package:fl_chart/fl_chart.dart';
import '../models/psychological_test.dart';
import '../models/database_helper.dart';
import 'package:intl/intl.dart';

class TestReportScreen extends StatefulWidget {
  final TestRecord record;

  const TestReportScreen({
    Key? key,
    required this.record,
  }) : super(key: key);

  @override
  State<TestReportScreen> createState() => _TestReportScreenState();
}

class _TestReportScreenState extends State<TestReportScreen> {
  List<TestRecord> historyRecords = [];
  bool isLoading = true;

  @override
  void initState() {
    super.initState();
    _loadHistoryRecords();
  }

  Future<void> _loadHistoryRecords() async {
    try {
      final records = await DatabaseHelper.instance.getTestRecordsByType(widget.record.testType);
      setState(() {
        historyRecords = records;
        isLoading = false;
      });
    } catch (e) {
      setState(() => isLoading = false);
    }
  }

  String _getTestTitle() {
    switch (widget.record.testType) {
      case TestType.SDS:
        return '抑郁自评量表(SDS)';
      case TestType.SAS:
        return '焦虑自评量表(SAS)';
      case TestType.SCL90:
        return '症状自评量表(SCL-90)';
    }
  }

  String _getScoreDescription(double score) {
    if (widget.record.testType == TestType.SCL90) {
      if (score < 1.5) {
        return '根据量表得分显示，您目前的状态处于正常范围内。建议您继续保持良好的生活习惯和心理状态。';
      } else if (score < 2.5) {
        return '量表结果提示您可能存在一些心理困扰。建议您关注自己的心理健康，必要时可以寻求专业的心理咨询支持。';
      } else {
        return '量表结果显示您当前的心理状态需要关注。建议您及时寻求专业的心理健康服务，获取适当的支持和帮助。';
      }
    } else {
      if (score < 50) {
        return '根据量表得分显示，您目前的状态处于正常范围内。建议您继续保持良好的生活习惯和心理状态。';
      } else if (score < 60) {
        return '量表结果提示您可能存在一些情绪困扰。建议您关注自己的心理健康，必要时可以寻求专业的心理咨询支持。';
      } else {
        return '量表结果显示您当前的情绪状态需要关注。建议您及时寻求专业的心理健康服务，获取适当的支持和帮助。';
      }
    }
  }

  Color _getScoreColor(double score) {
    if (widget.record.testType == TestType.SCL90) {
      if (score < 1.5) return Colors.green;
      if (score < 2.5) return Colors.orange;
      return Colors.red;
    } else {
      if (score < 50) return Colors.green;
      if (score < 60) return Colors.orange;
      return Colors.red;
    }
  }

  Widget _buildScoreSection() {
    // 计算SCL-90的总分
    double standardScore;
    if (widget.record.testType == TestType.SCL90) {
      double sum = widget.record.answers.reduce((a, b) => a + b).toDouble();
      standardScore = sum / 90; // SCL-90总分为所有90个项目的平均分
    } else {
      standardScore = widget.record.standardScore;
    }

    return Container(
      padding: const EdgeInsets.all(20),
      decoration: BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.circular(15),
        border: Border.all(color: Colors.grey.shade200),
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: [
              Text(
                widget.record.testType == TestType.SCL90 ? '总均分' : '标准分',
                style: GoogleFonts.zcoolKuaiLe(
                  fontSize: 22,
                  color: Colors.black54,
                ),
              ),
              Text(
                widget.record.testType == TestType.SCL90
                    ? '${standardScore.toStringAsFixed(2)} 分'
                    : '${standardScore.toStringAsFixed(0)} 分',
                style: GoogleFonts.zcoolKuaiLe(
                  fontSize: 36,
                  fontWeight: FontWeight.bold,
                  color: _getScoreColor(standardScore),
                ),
              ),
            ],
          ),
          const SizedBox(height: 16),
          ClipRRect(
            borderRadius: BorderRadius.circular(10),
            child: LinearProgressIndicator(
              value: widget.record.testType == TestType.SCL90
                  ? standardScore / 4 // SCL-90最高分为4分
                  : standardScore / 100, // SDS/SAS最高分为100分
              backgroundColor: Colors.grey[100],
              valueColor: AlwaysStoppedAnimation<Color>(
                _getScoreColor(standardScore),
              ),
              minHeight: 8,
            ),
          ),
          const SizedBox(height: 16),
          Text(
            _getScoreDescription(standardScore),
            style: GoogleFonts.zcoolKuaiLe(
              fontSize: 18,
              color: Colors.black87,
              height: 1.5,
            ),
          ),
        ],
      ),
    );
  }

  Widget _buildDimensionAnalysis() {
    if (widget.record.testType == TestType.SCL90) {
      // 直接使用答案列表
      final List<int> answers = widget.record.answers;
      
      // SCL-90维度题目对应关系
      final dimensionQuestions = {
        '躯体化': [1, 4, 12, 27, 40, 42, 48, 49, 52, 53, 56, 58],
        '强迫': [3, 9, 10, 28, 38, 45, 46, 51, 55, 65],
        '人际关系敏感': [6, 21, 34, 36, 37, 41, 61, 69, 73],
        '抑郁': [5, 14, 15, 20, 22, 26, 29, 30, 31, 32, 54, 71, 79],
        '焦虑': [2, 17, 23, 33, 39, 57, 72, 78, 80, 86],
        '敌对': [11, 24, 63, 67, 74, 81],
        '恐怖': [13, 25, 47, 50, 70, 75, 82],
        '偏执': [8, 18, 43, 68, 76, 83],
        '精神病性': [7, 16, 35, 62, 77, 84, 85, 87, 88, 90],
        '其他': [19, 44, 59, 60, 64, 66, 89],
      };

      // SCL-90维度题目对应关系和图标
      final dimensionIcons = {
        '躯体化': Icons.accessibility_new,
        '强迫': Icons.loop,
        '人际关系敏感': Icons.people_alt,
        '抑郁': Icons.mood_bad,
        '焦虑': Icons.warning_amber,
        '敌对': Icons.flash_on,
        '恐怖': Icons.crisis_alert,
        '偏执': Icons.psychology,
        '精神病性': Icons.blur_on,
        '其他': Icons.more_horiz,
      };

      // 计算各维度的平均分
      Map<String, double> dimensionScores = {};
      dimensionQuestions.forEach((dimension, questions) {
        double sum = 0;
        for (int questionIndex in questions) {
          // SCL-90的题目从1开始编号，而数组索引从0开始
          sum += answers[questionIndex - 1];
        }
        dimensionScores[dimension] = sum / questions.length;
      });

      // 维度说明
      final dimensionDescriptions = {
        '躯体化': '反映身体不适感，包括心血管、胃肠道、呼吸及其他系统的主观痛苦',
        '强迫': '反映强迫思维、冲动及行为，注意力难以集中等',
        '人际关系敏感': '反映人际交往中的自卑感、不自在感及人际敏感',
        '抑郁': '反映心境低落、兴趣丧失、动力缺乏、无望感等抑郁症状',
        '焦虑': '反映紧张、烦躁、担心等焦虑体验及相应的躯体表现',
        '敌对': '反映敌对、攻击等负面情绪状态',
        '恐怖': '反映对特定的人、场所、物品或情境的恐惧',
        '偏执': '反映猜疑、关系观念、妄想等偏执思维',
        '精神病性': '反映幻听、被控制感等思维广播以及精神病性行为',
        '其他': '包括睡眠和饮食等方面的症状',
      };

      final dimensions = dimensionScores.entries.map((entry) {
        return {
          'name': entry.key,
          'score': entry.value,
          'description': dimensionDescriptions[entry.key],
        };
      }).toList();

      // 按分数从高到低排序
      dimensions.sort((a, b) => (b['score'] as double).compareTo(a['score'] as double));

      return Container(
        padding: const EdgeInsets.all(20),
        decoration: BoxDecoration(
          color: Colors.white,
          borderRadius: BorderRadius.circular(15),
          border: Border.all(color: Colors.grey.shade200),
        ),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Text(
              '维度分析',
              style: GoogleFonts.zcoolKuaiLe(
                fontSize: 22,
                fontWeight: FontWeight.bold,
                color: Colors.black87,
              ),
            ),
            const SizedBox(height: 20),
            ...dimensions.map((dim) {
              final score = dim['score'] as double;
              String level = score < 2 ? '正常范围' : (score < 3 ? '轻度' : '中度');
              Color color = score < 2 ? Colors.green : (score < 3 ? Colors.orange : Colors.red);
              
              return Padding(
                padding: const EdgeInsets.only(bottom: 20),
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Row(
                      mainAxisAlignment: MainAxisAlignment.spaceBetween,
                      children: [
                        Expanded(
                          child: Column(
                            crossAxisAlignment: CrossAxisAlignment.start,
                            children: [
                              Row(
                                children: [
                                  Icon(
                                    dimensionIcons[dim['name']],
                                    size: 24,
                                    color: Colors.black54,
                                  ),
                                  const SizedBox(width: 8),
                                  Text(
                                    '${dim['name']} (${score.toStringAsFixed(2)})',
                                    style: GoogleFonts.zcoolKuaiLe(
                                      fontSize: 18,
                                      fontWeight: FontWeight.w500,
                                      color: Colors.black87,
                                    ),
                                  ),
                                ],
                              ),
                              const SizedBox(height: 4),
                              Text(
                                dim['description'] as String,
                                style: GoogleFonts.zcoolKuaiLe(
                                  fontSize: 16,
                                  color: Colors.black54,
                                ),
                              ),
                            ],
                          ),
                        ),
                        const SizedBox(width: 16),
                        Text(
                          level,
                          style: GoogleFonts.zcoolKuaiLe(
                            fontSize: 16,
                            color: color,
                          ),
                        ),
                      ],
                    ),
                    const SizedBox(height: 8),
                    Stack(
                      children: [
                        Container(
                          width: double.infinity,
                          height: 6,
                          decoration: BoxDecoration(
                            color: Colors.grey[100],
                            borderRadius: BorderRadius.circular(3),
                          ),
                        ),
                        FractionallySizedBox(
                          widthFactor: score / 4, // 最高分为4
                          child: Container(
                            height: 6,
                            decoration: BoxDecoration(
                              color: color,
                              borderRadius: BorderRadius.circular(3),
                            ),
                          ),
                        ),
                      ],
                    ),
                  ],
                ),
              );
            }).toList(),
            const SizedBox(height: 16),
            Text(
              '* 维度分数说明：\n'
              '1.0-2.0: 正常范围（一般人群的平均水平）\n'
              '2.0-3.0: 轻度（高于一般人群平均水平）\n'
              '3.0-4.0: 中度（明显高于一般人群平均水平）\n'
              '\n'
              '注意事项：\n'
              '1. 本测评结果仅供参考，不作为临床诊断依据\n'
              '2. 如果您对某些维度的得分感到困扰，建议咨询专业心理医生\n'
              '3. 建议定期进行评估，关注自己的心理健康变化',
              style: GoogleFonts.zcoolKuaiLe(
                fontSize: 14,
                color: Colors.black54,
                height: 1.5,
              ),
            ),
          ],
        ),
      );
    } else {
      // SDS/SAS的分析部分
      final List<int> answers = widget.record.answers;
      
      // SDS/SAS维度定义
      final dimensions = widget.record.testType == TestType.SDS ? {
        '情感症状': [1, 3, 4, 7, 8, 9, 10, 13, 15, 19],
        '躯体症状': [2, 5, 6, 11, 12, 14, 16, 18],
        '精神运动性症状': [17, 20],
      } : {
        '主观感受': [1, 2, 3, 4, 5],
        '躯体症状': [6, 7, 8, 9, 10, 11, 12, 13],
        '认知功能': [14, 15, 16, 17, 18, 19, 20],
      };

      // SDS维度图标
      final sdsIcons = {
        '情感症状': Icons.sentiment_dissatisfied,
        '躯体症状': Icons.accessibility_new,
        '精神运动性症状': Icons.psychology,
      };

      // SAS维度图标
      final sasIcons = {
        '主观感受': Icons.face,
        '躯体症状': Icons.accessibility_new,
        '认知功能': Icons.psychology,
      };

      // 获取当前量表的图标映射
      final currentIcons = widget.record.testType == TestType.SDS ? sdsIcons : sasIcons;

      // 计算各维度得分
      Map<String, double> dimensionScores = {};
      dimensions.forEach((dimension, questions) {
        double sum = 0;
        for (int questionIndex in questions) {
          sum += answers[questionIndex - 1];
        }
        // 计算维度原始分
        double rawScore = sum / questions.length;
        // 转换为标准分（SDS和SAS的计算方法相同：原始分之和 × 1.25）
        dimensionScores[dimension] = rawScore;
      });

      // 维度说明
      final dimensionDescriptions = widget.record.testType == TestType.SDS ? {
        '情感症状': '反映抑郁的核心症状，包括情绪低落、悲观、易哭等',
        '躯体症状': '反映睡眠、饮食、性欲等方面的改变',
        '精神运动性症状': '反映思维和行为的迟滞或激越',
      } : {
        '主观感受': '反映紧张、担心、恐惧等主观焦虑体验',
        '躯体症状': '反映心悸、出汗、手抖等自主神经症状',
        '认知功能': '反映注意力、记忆力等认知功能的改变',
      };

      return Container(
        padding: const EdgeInsets.all(20),
        decoration: BoxDecoration(
          color: Colors.white,
          borderRadius: BorderRadius.circular(15),
          border: Border.all(color: Colors.grey.shade200),
        ),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Text(
              '维度分析',
              style: GoogleFonts.zcoolKuaiLe(
                fontSize: 22,
                fontWeight: FontWeight.bold,
                color: Colors.black87,
              ),
            ),
            const SizedBox(height: 20),
            ...dimensionScores.entries.map((entry) {
              final score = entry.value;
              String level;
              Color color;
              
              // 根据原始分判断程度
              if (score < 2) {
                level = '正常';
                color = Colors.green;
              } else if (score < 2.5) {
                level = '轻度';
                color = Colors.orange;
              } else if (score < 3) {
                level = '中度';
                color = Colors.deepOrange;
              } else {
                level = '重度';
                color = Colors.red;
              }

              return Padding(
                padding: const EdgeInsets.only(bottom: 20),
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Row(
                      mainAxisAlignment: MainAxisAlignment.spaceBetween,
                      children: [
                        Expanded(
                          child: Column(
                            crossAxisAlignment: CrossAxisAlignment.start,
                            children: [
                              Row(
                                children: [
                                  Icon(
                                    currentIcons[entry.key],
                                    size: 24,
                                    color: Colors.black54,
                                  ),
                                  const SizedBox(width: 8),
                                  Text(
                                    '${entry.key} (${score.toStringAsFixed(2)})',
                                    style: GoogleFonts.zcoolKuaiLe(
                                      fontSize: 18,
                                      fontWeight: FontWeight.w500,
                                      color: Colors.black87,
                                    ),
                                  ),
                                ],
                              ),
                              const SizedBox(height: 4),
                              Text(
                                dimensionDescriptions[entry.key]!,
                                style: GoogleFonts.zcoolKuaiLe(
                                  fontSize: 16,
                                  color: Colors.black54,
                                ),
                              ),
                            ],
                          ),
                        ),
                        const SizedBox(width: 16),
                        Text(
                          level,
                          style: GoogleFonts.zcoolKuaiLe(
                            fontSize: 16,
                            color: color,
                          ),
                        ),
                      ],
                    ),
                    const SizedBox(height: 8),
                    Stack(
                      children: [
                        Container(
                          width: double.infinity,
                          height: 6,
                          decoration: BoxDecoration(
                            color: Colors.grey[100],
                            borderRadius: BorderRadius.circular(3),
                          ),
                        ),
                        FractionallySizedBox(
                          widthFactor: score / 4, // 最高分为4分
                          child: Container(
                            height: 6,
                            decoration: BoxDecoration(
                              color: color,
                              borderRadius: BorderRadius.circular(3),
                            ),
                          ),
                        ),
                      ],
                    ),
                  ],
                ),
              );
            }).toList(),
            const SizedBox(height: 16),
            Text(
              widget.record.testType == TestType.SDS
                  ? '* 维度分析说明：\n'
                    '< 2.0分: 正常范围\n'
                    '2.0-2.5分: 轻度\n'
                    '2.5-3.0分: 中度\n'
                    '≥ 3.0分: 重度\n'
                    '\n'
                    '注意事项：\n'
                    '1. 维度分析显示了各方面症状的严重程度\n'
                    '2. 建议定期评估，关注症状变化'
                  : '* 维度分析说明：\n'
                    '< 2.0分: 正常范围\n'
                    '2.0-2.5分: 轻度\n'
                    '2.5-3.0分: 中度\n'
                    '≥ 3.0分: 重度\n'
                    '\n'
                    '注意事项：\n'
                    '1. 维度分析显示了各方面症状的严重程度\n'
                    '2. 建议定期评估，关注症状变化',
              style: GoogleFonts.zcoolKuaiLe(
                fontSize: 14,
                color: Colors.black54,
                height: 1.5,
              ),
            ),
          ],
        ),
      );
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.grey[50],
      appBar: AppBar(
        backgroundColor: Colors.white,
        elevation: 0,
        leading: IconButton(
          icon: const Icon(Icons.arrow_back_ios, color: Colors.black),
          onPressed: () => Navigator.pop(context),
        ),
        title: Text(
          _getTestTitle(),
          style: GoogleFonts.zcoolKuaiLe(
            fontSize: 20,
            fontWeight: FontWeight.bold,
            color: Colors.black,
          ),
        ),
        centerTitle: true,
        actions: [
          IconButton(
            icon: const Icon(Icons.share_outlined, color: Colors.black),
            onPressed: () {
              // TODO: Implement share functionality
            },
          ),
        ],
      ),
      body: isLoading
          ? const Center(child: CircularProgressIndicator())
          : SingleChildScrollView(
              padding: const EdgeInsets.all(16),
              child: Column(
                children: [
                  Text(
                    DateFormat('yyyy年MM月dd日').format(widget.record.testDate),
                    style: GoogleFonts.zcoolKuaiLe(
                      fontSize: 16,
                      color: Colors.black54,
                    ),
                  ),
                  const SizedBox(height: 16),
                  _buildScoreSection(),
                  const SizedBox(height: 16),
                  _buildDimensionAnalysis(),
                  const SizedBox(height: 24),
                  Container(
                    width: double.infinity,
                    padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 12),
                    decoration: BoxDecoration(
                      color: Colors.grey[50],
                      borderRadius: BorderRadius.circular(8),
                    ),
                    child: Text(
                      '本测评结果仅供参考，不能替代专业医疗诊断。如有需要，请及时就医。',
                      style: GoogleFonts.zcoolKuaiLe(
                        fontSize: 14,
                        color: Colors.black54,
                        height: 1.5,
                      ),
                      textAlign: TextAlign.center,
                    ),
                  ),
                  const SizedBox(height: 16),
                ],
              ),
            ),
    );
  }
} 